//
//  NetworkTools.swift
//  Weibo
//
//  Created by 冯童童 on 16/1/22.
//  Copyright © 2016年 冯童童. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethods : String {
    
    case POST = "POST"
    case GET = "GET"
}

private let hostName = "https://api.weibo.com/"
private let WBDomain = "com.weibo.data.error"
class NetworkTools: AFHTTPSessionManager {

    
    static let sharedTools : NetworkTools = {
        let url = NSURL(string: hostName)
        let tools = NetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    
    func requestJSONDict( method : HTTPMethods, urlString : String, parameters : [String : AnyObject]?, finished : (dict: [String : AnyObject]?, error : NSError?) -> ()) {
        if method == HTTPMethods.POST {
            
            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                print(result)
                
                guard let dict = result as? [String : AnyObject] else {
                    
                    print("数据不合法")
                    let myError = NSError(domain: WBDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
                    finished(dict: nil, error: myError)
                    return
                }
                finished(dict: dict, error: nil)
                
                }) { (_, error) -> Void in
                    print(error)
                    finished(dict: nil, error: error)
            }
            
        }else {
            
            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
                print(result)
                
                guard let dict = result as? [String : AnyObject] else {
                    
                    print("数据不合法")
                    let myError = NSError(domain: WBDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
                    finished(dict: nil, error: myError)
                    return
                }
                finished(dict: dict, error: nil)
                
                }) { (_, error) -> Void in
                    print(error)
                    finished(dict: nil, error: error)
            }
            

            
        }

        }
    }
